package com.utils.network2.gank.parser;


import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.utils.network2.gank.entity.GankResponse;

import java.io.IOException;
import java.lang.reflect.Type;

import rxhttp.wrapper.annotation.Parser;
import rxhttp.wrapper.entity.ParameterizedTypeImpl;
import rxhttp.wrapper.exception.ParseException;
import rxhttp.wrapper.parse.AbstractParser;

/**
 * Response<T> 数据解析器,解析完成对Response对象做判断,如果ok,返回数据 T
 *
 * @param <T>
 */
@Parser(name = "GankResponse")
public class ResponseParser<T> extends AbstractParser<MutableLiveData<T>> {

    protected ResponseParser() {
        super();
    }

    public ResponseParser(Class<T> type) {
        super(type);
    }

    @SuppressWarnings("unchecked")
    @Override
    public MutableLiveData<T> onParse(okhttp3.Response response) throws IOException {
        final Type type = ParameterizedTypeImpl.get(GankResponse.class, mType); //获取泛型类型
        GankResponse<MutableLiveData<T>> data = convert(response, type);
        T results = (T) data.getResults(); //获取data字段
        MutableLiveData<T> t = new MutableLiveData<>(results); //获取data字段
        //t.postValue(results);

        if (data.isError()) {//code不等于0，说明数据不正确，抛出异常
            throw new ParseException("-1", "", response);
        }
        return t;
    }
}
